package com.xc.file.web.rest;

import com.xc.api.basic.BasicApi;
import com.xc.config.aspect.AspectConstants;
import com.xc.core.annotation.Authority;
import com.xc.core.bean.*;
import com.xc.core.dto.*;
import com.xc.core.enums.CaptchaType;
import com.xc.core.enums.InfoType;
import com.xc.core.enums.RedisPrefix;
import com.xc.core.enums.SignType;
import com.xc.core.model.TokenModel;
import com.xc.core.utils.RedisUtils;
import com.xc.file.entity.UserInfoEntity;
import com.xc.file.service.UserInfoService;
import com.xc.tool.utils.JSONUtils;
import com.xc.tool.utils.ObjectUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>我的授权,调用开放接口</p>
 *
 * @author xc
 * @version v1.0.0
 */
@Api(tags = {"我的授权,调用开放接口"})
@RestController
public class MyAppRest {
    @Autowired
    private AspectConstants aspectConstants;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private BasicApi basicApi;

    @ApiOperation(value = "获取参数信息")
    @GetMapping("/my_app/info")
    public List<InfoDto> getMyAppInfo() {
        SignBean signBean = new SignBean(aspectConstants.getAppId(), aspectConstants.getAppSecret(), SignType.MD5_SIGN);
        return basicApi.getOpenInfoList(signBean, InfoType.CLIENT_INFO.getType());
    }

    @ApiOperation(value = "获取区域集合", notes = "根据父级code获取区域集合，不传code获取顶级区域")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "父级节点,为null查询全部", name = "parentNode", paramType = "query"),
    })
    @GetMapping("/my_app/area_list")
    @Authority
    public List<AreaDto> getMyAppAreaList(@RequestParam(required = false) String parentNode) {
        SignBean signBean = new SignBean(aspectConstants.getAppId(), aspectConstants.getAppSecret(), SignType.MD5_SIGN);
        return basicApi.getOpenAreaList(signBean, parentNode);
    }

    @ApiOperation(value = "获取菜单集合")
    @GetMapping("/my_app/menu_list")
    public List<AuthorityDto> getMyAppMenuList() {
        SignBean signBean = new SignBean(aspectConstants.getAppId(), aspectConstants.getAppSecret(), SignType.MD5_SIGN);
        return basicApi.getOpenMenuList(signBean);
    }

    @ApiOperation(value = "获取字典集合")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "字典类型,为null查询全部", name = "type", paramType = "query"),
    })
    @GetMapping("/my_app/dict_list")
    public List<DictDto> getMyAppDictList(@RequestParam(required = false) String type) {
        SignBean signBean = new SignBean(aspectConstants.getAppId(), aspectConstants.getAppSecret(), SignType.MD5_SIGN);
        return basicApi.getOpenDictList(signBean, type);
    }


    @ApiOperation(value = "获取token")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "授权code", name = "code", paramType = "query", required = true),
    })
    @GetMapping("/my_app/token")
    public TokenDto getMyAppToken(@RequestParam(required = false) String code, @RequestParam(required = false) String accessToken) {
        SignBean signBean = new SignBean(aspectConstants.getAppId(), aspectConstants.getAppSecret(), SignType.MD5_SIGN);
        TokenModel tokenModel = basicApi.getOpenToken(signBean, code, accessToken);
        // 创建本地用户信息
        UserInfoEntity userInfoEntity = userInfoService.getUserInfoByUserId(tokenModel.getUserId());
        if (userInfoEntity == null) {
            UserInfoEntity userInfo = new UserInfoEntity();
            userInfo.setUserId(tokenModel.getUserId());
            userInfo.setAccount(tokenModel.getAccount());
            userInfoService.createUserInfo(userInfo);
        }
        RedisUtils.set(RedisPrefix.ACCESS.getKey() + tokenModel.getAccessToken(), JSONUtils.getStringByObject(tokenModel));
        return ObjectUtils.convert(new TokenDto(), tokenModel);
    }

    @ApiOperation(value = "退出登录", notes = "删除当前我的应用的token信息")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户token", name = "token", paramType = "header", required = true)
    })
    @DeleteMapping("/my_app/token")
    @Authority
    public void deleteMyAppToken(TokenModel tokenModel) {
        SignBean signBean = new SignBean(aspectConstants.getAppId(), aspectConstants.getAppSecret(), SignType.MD5_SIGN);
        // 删除文件授权
        String key = RedisPrefix.USER_DOWNLOAD.getKey() + tokenModel.getUserId();
        RedisUtils.delete(key);
        // 删除本地token
        RedisUtils.delete(RedisPrefix.ACCESS.getKey() + tokenModel.getAccessToken());
        basicApi.deleteOpenToken(signBean, tokenModel.getAccessToken());
    }

    @ApiOperation(value = "刷新token信息")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "刷新token", name = "refreshToken", paramType = "path", required = true),
    })
    @PutMapping("/my_app/token/{refreshToken}")
    public TokenDto updateMyAppToken(@PathVariable String refreshToken) {
        SignBean signBean = new SignBean(aspectConstants.getAppId(), aspectConstants.getAppSecret(), SignType.MD5_SIGN);
        TokenModel tokenModel = basicApi.updateOpenToken(signBean, refreshToken);
        RedisUtils.set(RedisPrefix.ACCESS.getKey() + tokenModel.getAccessToken(), JSONUtils.getStringByObject(tokenModel));
        return ObjectUtils.convert(new TokenDto(), tokenModel);
    }

    @ApiOperation(value = "获取当前用户信息")
    @GetMapping("/my_app/user_info")
    @Authority
    public UserInfoDto getMyAppUserInfo(TokenModel tokenModel) {
        SignBean signBean = new SignBean(aspectConstants.getAppId(), aspectConstants.getAppSecret(), SignType.MD5_SIGN);
        return basicApi.getOpenUserInfo(signBean, tokenModel.getUserId());
    }

    @ApiOperation(value = "修改当前用户信息")
    @PutMapping("/my_app/user_info")
    @Authority
    public UserInfoDto updateMyAppUserInfo(TokenModel tokenModel, @RequestBody UserInfoBean userInfoBean) {
        SignBean signBean = new SignBean(aspectConstants.getAppId(), aspectConstants.getAppSecret(), SignType.MD5_SIGN);
        return basicApi.updateOpenUserInfo(signBean, tokenModel.getUserId(), userInfoBean);
    }

    @ApiOperation(value = "获取用户", notes = "获取我的应用下的用户")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户token", name = "token", paramType = "header", required = true)
    })
    @GetMapping("/my_app/user")
    @Authority
    public UserDto getMyAppUser(TokenModel tokenModel) {
        SignBean signBean = new SignBean(aspectConstants.getAppId(), aspectConstants.getAppSecret(), SignType.MD5_SIGN);
        return basicApi.getOpenUser(signBean, tokenModel.getUserId());
    }

    @ApiOperation(value = "修改密码", notes = "修改我的应用下的用户密码")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户token", name = "token", paramType = "header", required = true),
    })
    @PutMapping("/my_app/user/password")
    @Authority
    public UserDto updateMyAppUserPassword(TokenModel tokenModel, @RequestBody PasswordBean passwordBean) {
        SignBean signBean = new SignBean(aspectConstants.getAppId(), aspectConstants.getAppSecret(), SignType.MD5_SIGN);
        return basicApi.updateOpenUserPassword(signBean, tokenModel.getUserId(), passwordBean);
    }

    @ApiOperation(value = "修改用户邮箱")
    @PutMapping("/my_app/user/email")
    @Authority
    public UserDto updateMyAppUserMail(TokenModel tokenModel, @RequestBody UpdateMailBean updateMailBean) {
        SignBean signBean = new SignBean(aspectConstants.getAppId(), aspectConstants.getAppSecret(), SignType.MD5_SIGN);
        return basicApi.updateOpenUserMail(signBean, tokenModel.getUserId(), updateMailBean);
    }

    @ApiOperation(value = "修改用户手机号")
    @PutMapping("/my_app/user/phone")
    @Authority
    public UserDto updateMyAppUserPhone(TokenModel tokenModel, @RequestBody UpdatePhoneBean updatePhoneBean) {
        SignBean signBean = new SignBean(aspectConstants.getAppId(), aspectConstants.getAppSecret(), SignType.MD5_SIGN);
        return basicApi.updateOpenUserPhone(signBean, tokenModel.getUserId(), updatePhoneBean);
    }

    @ApiOperation(value = "发送验证码")
    @PostMapping("/my_app/send_captcha")
    @Authority
    public void myAppSendCaptcha(TokenModel tokenModel, @RequestBody CaptchaBean captchaBean) {
        if (CaptchaType.UNSUBSCRIBE.getType().equals(captchaBean.getCaptchaType())) {
            captchaBean.setUserId(tokenModel.getUserId());
        }
        SignBean signBean = new SignBean(aspectConstants.getAppId(), aspectConstants.getAppSecret(), SignType.MD5_SIGN);
        basicApi.createOpenSendCaptcha(signBean, captchaBean);
    }

    @ApiOperation(value = "获取用户集合")
    @GetMapping("/my_app/user_list")
    @Authority
    public List<Map<String, String>> getMyAppUserList() {
        SignBean signBean = new SignBean(aspectConstants.getAppId(), aspectConstants.getAppSecret(), SignType.MD5_SIGN);
        List<UserInfoDto> userInfos = basicApi.getOpenUserInfoList(signBean, null);
        List<Map<String, String>> mapList = new ArrayList<>();
        for (UserInfoDto userInfoDto : userInfos) {
            Map<String, String> map = new HashMap<>();
            map.put("userId", userInfoDto.getId());
            map.put("nickName", userInfoDto.getNickName());
            mapList.add(map);
        }
        return mapList;
    }

    @ApiOperation(value = "注销账户", notes = "删除用户")
    @DeleteMapping("/my_app/user")
    @Authority
    public UserDto deleteMyAppUser(TokenModel tokenModel, @RequestParam String captcha) {
        SignBean signBean = new SignBean(aspectConstants.getAppId(), aspectConstants.getAppSecret(), SignType.MD5_SIGN);
        return basicApi.deleteOpenUser(signBean, tokenModel.getUserId(), captcha);
    }

}
